# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - Flask应用初始化

这个文件包含Flask应用的工厂函数和扩展初始化
遵循Flask应用工厂模式，支持不同环境配置
"""

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, AnonymousUserMixin
from flask_wtf.csrf import CSRFProtect

# 自定义匿名用户类
class AnonymousUser(AnonymousUserMixin):
    """
    自定义匿名用户类

    为匿名用户添加角色检查方法
    避免模板中的AttributeError
    """

    def is_super_admin(self):
        """匿名用户不是超级管理员"""
        return False

    def is_campus_admin(self):
        """匿名用户不是校区管理员"""
        return False

    def is_coach(self):
        """匿名用户不是教练"""
        return False

    def is_student(self):
        """匿名用户不是学员"""
        return False


# 初始化Flask扩展实例
db = SQLAlchemy()
login_manager = LoginManager()
csrf = CSRFProtect()


def create_app():
    """
    Flask应用工厂函数

    Returns:
        Flask: 配置完成的Flask应用实例
    """
    # 创建Flask应用实例
    app = Flask(__name__)

    # 加载配置
    from app.config import Config
    app.config.from_object(Config)

    # 初始化扩展
    db.init_app(app)
    csrf.init_app(app)

    # 配置Flask-Login
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录以访问此页面。'
    login_manager.login_message_category = 'info'
    login_manager.session_protection = 'strong'
    login_manager.anonymous_user = AnonymousUser

    # 用户加载回调函数
    @login_manager.user_loader
    def load_user(user_id):
        """
        Flask-Login用户加载回调函数

        Args:
            user_id (str): 用户ID

        Returns:
            User: 用户对象或None
        """
        from app.models.user import User
        return User.query.get(int(user_id))

    # 注册蓝图
    register_blueprints(app)

    # 注册错误处理器
    register_error_handlers(app)

    return app


def register_blueprints(app):
    """
    注册应用蓝图

    Args:
        app (Flask): Flask应用实例
    """
    # 认证蓝图
    from app.views.auth import auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    # 仪表板蓝图
    from app.views.dashboard import dashboard_bp
    app.register_blueprint(dashboard_bp, url_prefix='/')

    # 校区管理蓝图
    from app.views.campus import campus_bp
    app.register_blueprint(campus_bp, url_prefix='/campus')

    # 球台管理蓝图
    from app.views.tables import tables_bp
    app.register_blueprint(tables_bp, url_prefix='/tables')

    # 教练管理蓝图
    from app.views.coaches import coaches_bp
    app.register_blueprint(coaches_bp, url_prefix='/coaches')

    # 学员管理蓝图
    from app.views.students import students_bp
    app.register_blueprint(students_bp, url_prefix='/students')

    # 个人资料蓝图
    from app.views.profile import profile_bp
    app.register_blueprint(profile_bp, url_prefix='/profile')

    # 学员教练关系蓝图
    from app.views.student_coach import student_coach_bp
    app.register_blueprint(student_coach_bp, url_prefix='/student-coach')

    # 教练学员管理蓝图
    from app.views.coach_student import coach_student_bp
    app.register_blueprint(coach_student_bp, url_prefix='/coach-student')

    # 师生关系管理蓝图（管理员）
    from app.views.relations import relations_bp
    app.register_blueprint(relations_bp, url_prefix='/relations')

    # 学员预约管理蓝图
    from app.views.student_reservations import student_reservations_bp
    app.register_blueprint(student_reservations_bp, url_prefix='/student-reservations')

    # 教练预约管理蓝图
    from app.views.coach_reservations import coach_reservations_bp
    app.register_blueprint(coach_reservations_bp, url_prefix='/coach-reservations')

    # 管理员预约管理蓝图
    from app.views.admin_reservations import admin_reservations_bp
    app.register_blueprint(admin_reservations_bp, url_prefix='/admin-reservations')

    # 评价管理蓝图
    from app.views.evaluations import evaluations_bp
    app.register_blueprint(evaluations_bp, url_prefix='/evaluations')

    # 账户管理蓝图
    from app.views.accounts import accounts_bp
    app.register_blueprint(accounts_bp, url_prefix='/accounts')

    # 管理员账户管理蓝图
    from app.views.admin_accounts import admin_accounts_bp
    app.register_blueprint(admin_accounts_bp, url_prefix='/admin-accounts')

    # 错误处理蓝图
    from app.views.errors import errors_bp
    app.register_blueprint(errors_bp)


def register_error_handlers(app):
    """
    注册错误处理器

    Args:
        app (Flask): Flask应用实例
    """
    @app.errorhandler(404)
    def not_found_error(error):
        """404错误处理"""
        from flask import render_template
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def internal_error(error):
        """500错误处理"""
        from flask import render_template
        db.session.rollback()
        return render_template('errors/500.html'), 500

    @app.errorhandler(403)
    def forbidden_error(error):
        """403错误处理"""
        from flask import render_template
        return render_template('errors/403.html'), 403
